package com.panda.web.controller.system;

import com.panda.common.exception.file.InvalidExtensionException;
import com.panda.common.utils.uuid.UUID;
import com.panda.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.panda.common.annotation.Log;
import com.panda.common.config.PandaConfig;
import com.panda.common.core.controller.BaseController;
import com.panda.common.core.domain.AjaxResult;
import com.panda.common.core.domain.entity.SysUser;
import com.panda.common.core.domain.model.LoginUser;
import com.panda.common.enums.BusinessType;
import com.panda.common.utils.SecurityUtils;
import com.panda.common.utils.StringUtils;
import com.panda.common.utils.file.FileUploadUtils;
import com.panda.common.utils.file.MimeTypeUtils;
import com.panda.framework.web.service.TokenService;
import com.panda.system.service.ISysUserService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 个人信息 业务处理
 *
 * @author panda
 */
@CrossOrigin
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysUserMapper userMapper;
    @Value("${file.upload-avatar}")
    private String uploadAvatar;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0) {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
            SysUser sysUser = userMapper.selectUserById(loginUser.getUserId());
            sysUser.setYuanPassword(newPassword);
            userMapper.updateUser(sysUser);

            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }


    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile avatarfile, HttpServletRequest request) throws IOException, InvalidExtensionException {
        if (!avatarfile.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(PandaConfig.getAvatarPath(), avatarfile, MimeTypeUtils.IMAGE_EXTENSION);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
//
//        LoginUser loginUser = getLoginUser();
//        String domain = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
//
//        // 使用 UUID 生成文件名，并确保文件名只包含合法字符
//        String originalFileName = UUID.randomUUID().toString() + ".png";  // 使用 UUID 生成唯一的文件名，并指定文件类型为 .png
//
//        // 清理文件名，确保只有合法字符
//        String cleanedFileName = originalFileName.replaceAll("[^\\u4E00-\\u9FA5a-zA-Z0-9-_\\.]", "_");
//
//        // 获取当前日期，格式化为yyyy/MM/dd
//        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//        String uploadAvatarPath = uploadAvatar + "/" + datePath; // 日期目录
//
//        // 创建日期相关的上传目录（如果不存在）
//        File uploadDirFile = new File(uploadAvatarPath);
//        if (!uploadDirFile.exists()) {
//            if (!uploadDirFile.mkdirs()) {
//                return error("无法创建上传目录，请联系管理员");
//            }
//        } else if (!uploadDirFile.isDirectory()) {
//            return error("上传目录无效，请联系管理员");
//        }
//
//        // 文件上传路径
//        File uploadFile = new File(uploadDirFile, cleanedFileName);
//        try {
//            avatarfile.transferTo(uploadFile);
//        } catch (IOException e) {
//            return error("文件上传失败，请联系管理员");
//        }
//
//        // 获取上传文件的完整路径
//        String uploadedFilePath = uploadFile.getAbsolutePath();
//
//        // 构建下载 URL
//        String fileDownloadUri = domain + "/file/avatar/" + URLEncoder.encode(datePath + "/" + cleanedFileName, StandardCharsets.UTF_8);
//
//        // 更新用户头像
//        if (userService.updateUserAvatar(loginUser.getUsername(), fileDownloadUri)) {
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("imgUrl", fileDownloadUri);
//            ajax.put("filePath", uploadedFilePath); // 展示文件路径
////            ajax.put("uploadDate", datePath); // 返回日期
//            loginUser.getUser().setAvatar(fileDownloadUri);
//            tokenService.setLoginUser(loginUser);
//            return ajax;
//        }
//
//        return error("更新用户头像失败，请稍后再试");
//    }
//
//    // 错误处理函数
//    public AjaxResult error(String message) {
//        AjaxResult result = new AjaxResult();
//        result.put("code", 500);
//        result.put("msg", message);
//        return result;
    }
}
